//
//  BaseDetailViewController.swift
//  OverseasOnlineShopping
//
//  Created by 唐先才 on 16/3/9.
//  Copyright © 2016年 唐先才. All rights reserved.
//

import UIKit

class BaseDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UIWebViewDelegate  {

    var tableView = UITableView(frame: CGRect(x: 0, y: 0, width: WIDTH, height: HEIGHT - 44 - 64), style: .Grouped)
    var dataArray: NSMutableArray = []
    var commentDataArray: NSMutableArray = []
    var likeDataArray: NSMutableArray = []
    var parameters: NSDictionary?
    var pic_url: String?
    var headView: UIView?
    var headImage: UIImageView?
    var webHeight: CGFloat?
    var web = UIWebView()
    var modelWeb: TxcModel?
    var waitView = WaitLoadView(frame: UIScreen.mainScreen().bounds)

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        self.tabBarController?.tabBar.hidden = true
        self.title = "商品详情"
    }
    
    override func viewWillDisappear(animated: Bool) {
        super.viewWillDisappear(animated)
        self.tabBarController?.tabBar.hidden = false
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        createToolBar()
        createUI()
        view.addSubview(waitView)
    }
    
    func createToolBar() {
        let buttomView = BaseDetailButtomView(frame: CGRect(x: 0, y: HEIGHT - 44 - 64, width: WIDTH, height: 44))
        self.view.addSubview(buttomView)
    }
    
    func createUI() {
        tableView.dataSource = self
        tableView.delegate = self
        self.view.addSubview(tableView)
        let nib1 = UINib(nibName: "DetailCellOne", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib1, forCellReuseIdentifier: "detailCellOne")
        let nib3 = UINib(nibName: "DetailCellThree", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib3, forCellReuseIdentifier: "detailCellThree")
        let nib4 = UINib(nibName: "DetailCellFour", bundle: NSBundle.mainBundle())
        tableView.registerNib(nib4, forCellReuseIdentifier: "detailCellFour")
        
        headView = UIView()
        headImage = UIImageView()
        guard let headView = headView, headImage = headImage else {
            return
        }
        headView.frame = CGRect(x: 0, y: 0, width: WIDTH, height: 350)
        headView.backgroundColor = UIColor.whiteColor()
        headImage.frame = headView.frame
        headImage.contentMode = UIViewContentMode.ScaleAspectFit
        headView.addSubview(headImage)
        tableView.tableHeaderView = headView
    }

    func createWeb() {
        guard let modelWeb = self.dataArray[0] as? TxcModel else {
            print("model传值失败")
            return
        }
        web.frame = CGRect(x: 0, y: 0, width: WIDTH, height: 100)
        web.delegate = self
        web.scrollView.userInteractionEnabled = true
        web.scrollView.scrollEnabled = false
        guard let content = modelWeb.InfoContent else {
            return
        }
        //        let string = "<head><style>img{max-width:320px !important;}</style></head>" + content
        let string = "<head><style>img{max-width:300px !important;}</style></head>" + content
        web.loadHTMLString(string, baseURL: nil)
    }
    
    func numberOfSectionsInTableView(tableView: UITableView) -> Int {
        return 4
    }
    
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return 1
        } else if section == 1 {
            return 1
        } else if section == 2 {
            if self.commentDataArray.count > 0 {
                return self.commentDataArray.count + 1
            }
        }
        return self.likeDataArray.count + 1
    }
    
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        if indexPath.section == 0 {
            let detailCellOne = DetailCellOne.detailCellOneWith(tableView, dataArray: self.dataArray, indexPath: indexPath)
            return detailCellOne
        } else if indexPath.section == 1 {
            var cell1 = tableView.dequeueReusableCellWithIdentifier("cell1")
            if (cell1 == nil) {
                cell1 = UITableViewCell(style: .Default, reuseIdentifier: "cell1")
            }
            guard let webCell = cell1 else {
                print("cell1 解包失败")
                return UITableViewCell()
            }
            if self.dataArray.count > 0 {
                if let model = self.dataArray[indexPath.row] as? TxcModel {
                    modelWeb = model
                    webCell.contentView.addSubview(web)
                }
            }
            return webCell
        } else if indexPath.section == 2 {
            let detailCellThree = DetailCellThree.detailCellThreeWith(tableView, dataArray: self.commentDataArray, indexPath: indexPath)
            return detailCellThree
        } else if indexPath.section == 3 {
            let detailCellFour = DetailCellFour.detailCellFourWith(tableView, dataArray: self.likeDataArray, indexPath: indexPath)
            return detailCellFour
        }
        return UITableViewCell()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        let str = webView.stringByEvaluatingJavaScriptFromString("document.body.offsetHeight")
        webHeight = CGFloat((str! as NSString).floatValue)
        //        print("++++\(webHeight)+++++")
        guard let webH = webHeight else {
            return
        }
        web.frame = CGRect(x: 0, y: 0, width: WIDTH, height: webH)
        tableView.reloadData()
        waitView.removeFromSuperview()
    }
    
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        if indexPath.section == 0 {
            return 100
        } else if indexPath.section == 1 {
            return web.frame.size.height + 20
        } else if indexPath.section == 2 {
            if indexPath.row == 0 {
                return 30
            }
            if self.commentDataArray.count > 0 {
                guard let model = self.commentDataArray[indexPath.row - 1] as? TxcModel else {
                    return 0
                }
                if model.ReviewContent == nil {
                    return 40
                }
                return 80
            }
        } else if indexPath.section == 3 {
            if indexPath.row == 0 {
                return 30
            }
            return 100
        }
        return 0
    }
    
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 1 {
            return 1
        } else if section == 2{
            return 10
        } else if section == 3 {
            return 10
        }
        return 0
    }
    
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 1
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        guard let headImage = headImage else {
            return
        }
        var offset = tableView.contentOffset.y
        if offset > 0 {
            offset = 0
        }
        headImage.frame = CGRect(x: 0 + offset / 2, y: offset, width: WIDTH - offset * 0.8, height: 350 - offset)
    }


    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
